package com.self.match.boot;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.self.common.enums.OrderDirection;
import com.self.common.param.Order;
import com.self.match.disruptor.DisruptorTemplate;
import com.self.match.domain.EntrustOrder;
import com.self.match.mapper.EntrustOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @version v1.0
 * @ClassName: DataLoadRunner
 * @Description:
 * @Author: Mac
 */
@Slf4j
@Component
public class DataLoadRunner implements ApplicationRunner {

    @Autowired
    private EntrustOrderMapper entrustOrderMapper;
    @Autowired
    private DisruptorTemplate disruptorTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<EntrustOrder> entrustOrders = entrustOrderMapper.selectList(new LambdaQueryWrapper<EntrustOrder>()
                .eq(EntrustOrder::getStatus, 0)
                .orderByAsc(EntrustOrder::getCreated));
        if (!CollectionUtils.isEmpty(entrustOrders)){
            log.info("撮合委托单数量:{}",entrustOrders.size());
            for (EntrustOrder entrustOrder : entrustOrders){
                disruptorTemplate.start(entrustOrderConvertOrder(entrustOrder));
            }
        }
    }

    private Order entrustOrderConvertOrder(EntrustOrder entrustOrder) {
        Order order = new Order();
        // 设置交易对
        order.setSymbol(entrustOrder.getSymbol());
        // 设置交易额
        order.setAmount(entrustOrder.getVolume().add(entrustOrder.getDeal().negate()));
        // 设置交易价格
        order.setPrice(entrustOrder.getPrice());
        // 设置交易时间
        order.setTime(entrustOrder.getCreated().getTime());
        // 设置交易的id
        order.setOrderId(entrustOrder.getId().toString());
        // 设置交易的方向
        order.setOrderDirection(OrderDirection.getOrderDirection(entrustOrder.getType().intValue()));
        return order;
    }
}
